
# 文件通配符
import glob
print(glob.glob("*.py"), end="\n\n")

# 命令行参数
import sys
print(sys.argv, end="\n\n")

# 错误输出重定向
sys.stderr.write("sys.stderr.write()")

# 程序终止
#sys.exit()

# 字符串正则匹配
# re模块为高级字符串处理提供了正则表达式工具.
import re
print(re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest'))
print(re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat'))
print()

# 数学
# math模块为浮点运算提供了对底层C函数库的访问。
import math
print(math.cos(math.pi / 4))
print(math.log(1024, 2))
print()
# random模块提供了生成随机数的工具。
import random
print('choice:' , random.choice(['apple', 'pear', 'banana']))
print('sample:' , random.sample(range(100), 10))
print('random:' , random.random())      # float
print('randrange:' , random.randrange(6))  # integer
print()

# 访问互联网
# urllib.request模块用于处理从 urls 接收的数据.
'''
from urllib.request import urlopen
for line in urlopen("http://tycho.usno.navy.mil/cgi-bin/timer.pl"):
	line = line.decode('utf-8')  # Decoding the binary data to text.
	if 'EST' in line or 'EDT' in line:  # look for Eastern Time
		print(line)
'''
from urllib.request import urlopen
for line in urlopen("http://www.timedate.cn/worldclock/custom.asp?continent=asia&sort=0"):
	line = line.decode('gb2312')  # Decoding the binary data to text.
	if '当前北京时间' in line:  # look for Eastern Time
		sl = line.split('>')
		sl = sl[2].split('<')
		print("Beijing standard time:", sl[0])
print()
# smtplib模块用于发送电子邮件。
import smtplib
from email.mime.text import MIMEText
mail_from = "HaydnLiao@163.com"
mail_to = "HaydnLiao@qq.com"
mail_user = "HaydnLiao@163.com"
# mail_pass = "xxx"
try:
	content = "python smtplib moudle sends this e-mail!"
	msg = MIMEText(content)
	msg['From'] = mail_from
	msg['To'] = mail_to
	msg['Subject'] = "python smtplib test"
	print(msg.as_string())
	print('-'*20)
	server = smtplib.SMTP("smtp.163.com", 25)
	# server.login(mail_user, mail_pass)
	# server.sendmail(mail_from, mail_to, msg.as_string())
except Exception as e:
	print("<Exception>", e)
finally:
	rtn = server.quit()
	print("server.quit():", rtn)
print()

# 日期和时间
# datetime模块支持日期和时间算法的同时，将实现重点放在更有效的处理和格式化输出上。
from datetime import date
now = date.today()
print("date.today():", now)
paraList = ["%y %Y", "%m %b %B", "%d %D", "%a %A"]
for p in paraList:
	print('[' + p + ']: ' + now.strftime(p))
# print("date.ctime():", date.ctime(now))
# print(date.timetuple(now))
print()

# 数据压缩
# 支持通用的数据打包和压缩格式的模块：zlib，gzip，bz2，zipfile，以及 tarfile。
import zlib
s = b'witch which has which witches wrist watch'
print("origin:", len(s))
t = zlib.compress(s)
print("zlib:", len(t))
print(zlib.decompress(t))
print("crc32:", zlib.crc32(s))
import gzip
t = gzip.compress(s)
print("gzip:", len(t))
# print(gzip.decompress(t))
import bz2
t = bz2.compress(s)
print("bz2:", len(t))
# print(bz2.decompress(t))
print()

# 性能度量
# timeit模块提供了小代码片度量工具，显示解决同一问题的不同方法之间的性能差异。
from timeit import Timer
# 使用元组封装和拆封来交换元素要比传统的方法更好
print("Conventional:", Timer("t=a;a=b;b=t", "a=1;b=2").timeit())
print("Tuple:", Timer("a,b=b,a", "a=1;b=2").timeit())
# 异或交换耗时长
print("ExclusiveOr:", Timer("a^=b;b^=a;a^=b", "a=1;b=2").timeit())
print("Stack:", Timer("c=list();c.append(a);c.append(b);c.pop();c.pop()", "a=1;b=2").timeit())
print()

# 测试模块
# doctest模块提供了一个工具，扫描模块并根据程序中内嵌的文档字符串执行测试。
# 测试构造如同简单的将它的输出结果剪切并粘贴到文档字符串中。
# 通过用户提供的例子，它强化了文档，允许 doctest 模块确认代码的结果是否与文档一致。
def average(values):
	"""
	>>> print(average([20, 30, 70]))
	40.0
	"""
	return sum(values) / len(values)
import doctest
print(doctest.testmod())    # 自动验证嵌入average()
def test():
	"""
	>>> print(test())
	None
	"""
	return
import doctest
print(doctest.testmod())    # 自动验证嵌入测试test()
print()
# unittest模块可以在一个独立的文件里提供一个更全面的测试集.
import unittest
class TestStatisticalFunctions(unittest.TestCase):
	def test_average(self):
		self.assertEqual(average([20, 30, 70]), 40.0)
		self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
		self.assertRaises(ZeroDivisionError, average, [])
		self.assertRaises(TypeError, average, 20, 30, 70)
unittest.main() # Calling from the command line invokes all tests
